package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author 谢辉
 * @Classname ZipTestController
 * @Description TODO
 * @Date 2021/1/6 10:07
 */
@Controller
@RequestMapping("/zip")
public class ZipTestController {

    @RequestMapping("/get")
    public void getZip(HttpServletRequest request, HttpServletResponse response) throws Exception {

        ZipOutputStream zos = null;
        BufferedInputStream br = null;

        String[] filePath = {"D:\\111.png", "D:\\1110.png"};
        String[] fileName = {"111", "1110"};
        //下载方法
        try {
            //文件的名称
            String downloadFilename = "xieh.zip";
            response.reset();
            //设置格式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(downloadFilename, "UTF-8"));
            //ZipOutputStream来对文件压缩操作
            zos = new ZipOutputStream(response.getOutputStream());
            //循环下载文件，并将之放到ZipOutputStream中
            for (int i = 0; i < filePath.length; i++) {
                //filePath是下载路径集合
                //fileName是文件名称
                zos.putNextEntry(new ZipEntry(fileName[i] + ".png"));
                br = new BufferedInputStream(new FileInputStream(filePath[i]));
                byte[] buffer = new byte[1024];
                int r = 0;
                while ((r = br.read(buffer)) != -1) {
                    zos.write(buffer, 0, r);
                }
            }
            zos.flush();
        } catch (IOException e) {
            System.out.println("导出图片压缩包错误" + e);
        } finally {
            try {
                zos.close();
                br.close();
            } catch (IOException e) {
                System.out.println("导出图片关闭流异常" + e);
            }
        }
    }
}
